package com.handoop.gms.controller;

import com.handoop.gms.domain.Manager;
import com.handoop.gms.service.ManagerService;
import com.handoop.gms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import sun.misc.BASE64Encoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by Administrator on 2014-12-29.
 */
@Controller
@RequestMapping("/manage")
public class ManagerController extends BaseController{

    @Autowired
    private ManagerService service;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(){
        return "manage/manager/login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(String account,
                        String password,
                        Errors errors,
                        HttpSession session,
                        HttpServletResponse response){
        Manager manager = (Manager) service.login(account, password);
        if (manager==null){
            errors.rejectValue("account", "账号或密码错误！");
            return "manage/manager/login";
        }else {
            session.setAttribute(MANAGER_SESSION, manager);
            Cookie cookie = new Cookie("m_auto_login", new BASE64Encoder().encode(account.getBytes())+"_"
                    +new BASE64Encoder().encode(password.getBytes()));
            response.addCookie(cookie);
            return "redirect:/manage";
        }
    }
}
